package io.test.bio;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author chedx
 * @data 2021/4/8 10:35 PM
 */
public class BIOServerCP {
    private int port;
    ServerSocket serverSocket;

    public BIOServerCP(int port) {
        this.port = port;
        try {
            serverSocket = new ServerSocket(port);
            System.out.println("服务已经启动，监听的端口是：" +port);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void listen() throws IOException{
        while (true) {
            Socket client = serverSocket.accept();
            System.out.println(client.getPort());

            InputStream is = client.getInputStream();
            byte[] buff = new byte[1024];
            int len = is.read(buff);
            if(len>0) {
                String msg = new String(buff, 0, len);
                System.out.println("收到的消息是：" + msg);
            }
        }
    }


    public static void main(String[] args) throws IOException {
        new BIOServerCP(8080).listen();
    }
}
